package com.atguigu.cloud.predicate;

import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义配置 按照会员等级userType，按照钻、金、银、和yaml配置的等级来判断能否访问
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    //    配置类 断言规则，重要
    @Validated
    public static class Config {
        /**
         * 钻、金、银、和yaml配置的等级
         */
        @Getter
        @Setter
        @NotNull
        private String userType;

    }
    /**
     * DateTime key.
     */
    public static final String USERTYPE_KEY = "userType";


    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {

                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if (userType == null) {
                    return false;
                } else if (userType.equals(config.getUserType())) {
                    return true;
                }

                return false;
            }
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(USERTYPE_KEY);
    }


}
